package com.rfid.util;

import android.util.Log;

import com.rfid.rls_psw.App;
import com.rfid.util.FileUtil;
import com.rfid.util.Util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class NetUtil {

    public static OkHttpClient mOkHttpClient = new OkHttpClient();
    private static String TAG = "NetUtil";

    /**
     * 上传文件
     * @param filePath  本地文件地址
     */
    public static boolean upLoadFile(String requestUrl,String filePath) {
        //补全请求地址
//        String requestUrl = String.format("%s/%s", BASE_URL, "upload");
        //创建File
        File file = new File(filePath);
        //创建RequestBody
        RequestBody requestBody = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("file", file.getName(),
                        RequestBody.create(MediaType.parse("*/*"), new File(filePath)))
                .build();
        //创建Request
        final Request request = new Request.Builder().url(requestUrl).post(requestBody).build();
        final Call call = mOkHttpClient.newBuilder().writeTimeout(50, TimeUnit.SECONDS).build().newCall(request);
        try {
            Response response = call.execute();
            System.out.println(response.body().string());
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    public static void downloadFile(String url,String path) throws IOException {
        File file = new File(path);
        if(!file.getParentFile().exists()) {
            boolean s = file.getParentFile().mkdirs();
            Log.v(TAG,"mkdirs fail");
            return;
        }
        Request request = new Request.Builder().url(url).build();
        Response response = mOkHttpClient.newCall(request).execute();
        long total = response.body().contentLength();
        System.out.println("downloadFile total = " + total);
        InputStream in = response.body().byteStream();
//        FileUtil.StreamToFile(in,file);
        FileOutputStream fos = new FileOutputStream(file);
        int bufferSize = 1024 * 16;
        byte buffer[] = new byte[bufferSize];
        int len = 0;
        long current = 0;
        while((len = in.read(buffer,0,bufferSize)) != -1) {
            fos.write(buffer,0,len);
            current += len;
            Float r = current/(float)total * 100;
            App.getInstance().getObservable().notifyObservers(r);
        }
        fos.flush();
        fos.close();
        in.close();
    }
}
